import dayjs from 'dayjs'

export function formatDate(timestamp, fmt = 'YYYY-MM-DD HH:mm:ss') {
  if(!timestamp) {
    return ''
  }
  const str = timestamp + ''
  if (str.length === 10) {
    return dayjs.unix(timestamp).format(fmt)
  } else if (str.length === 13) {
    return dayjs(timestamp).format(fmt)
  }
}

function padLeftZero(str) {
  return ('00' + str).substr(str.length)
}

export function formatEnDate(timestamp) {
  var fmt = 'M DD, YYYY hh:mm:ss'
  if (timestamp == null || timestamp < 0) {
    return ''
  }
  var date = new Date()
  if (timestamp.toString().length === 13) {
    date.setTime(timestamp)
  } else if (timestamp.toString().length === 10) {
    date.setTime(timestamp * 1000)
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  }
  const o = {
    'M+': date.toLocaleString('en-US', { month: 'short' }),
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + ''
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      )
    }
  }
  return fmt
}
